import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:lib_database/src/config.dart';

import '../../provider/nav_key.dart';

class EasyLoading {
  factory EasyLoading() => _instance;
  static final EasyLoading _instance = EasyLoading._internal();

  EasyLoading._internal();

  static bool loading = false;

  static final FToast _fToast = FToast();

  static FToast get fToast => _fToast;

  static BuildContext get context => NavKey.navKey.currentContext!;

  static ensureFToastContextIsNotNull() {
    if (null == _fToast.context) {
      _fToast.init(context);
    }
  }

  static Future<T> generateLoadingFuture<T>(Future<T> f, {String? status, bool showErrorTip = true}) {
    Completer<T> completer = Completer();
    show(status: status);

    f.then((value) {
      dismiss();
      completer.complete(value);
    }).onError((error, stackTrace) {
      dismiss();
      if (showErrorTip) {
        showError(error.toString());
      }
      completer.completeError(error!, stackTrace);
    });

    return completer.future;
  }

  static void show({String? status}) {
    if (loading) return;
    loading = true;
    showDialog(
        context: context,
        barrierColor: const Color(0x00000001),
        barrierDismissible: false,
        routeSettings: const RouteSettings(name: 'LoadingDialog'),
        builder: (_) {
          return WillPopScope(
              child: Material(
                type: MaterialType.transparency,
                child: Center(
                  child: Container(
                    padding: EdgeInsets.all(14.w),
                    decoration: BoxDecoration(
                        color: Colors.black.withOpacity(0.8), borderRadius: BorderRadius.all(Radius.circular(12.w))),
                    child: Image.asset(
                      'assets/images/common/loading.gif',
                      width: 60.w,
                      height: 60.w,
                    ),
                  ),
                ),
              ),
              onWillPop: () async => false);
        });
  }

  static void dismiss() {
    if (loading) {
      Navigator.of(context).popUntil((route) {
        return route.settings.name != 'LoadingDialog';
      });
    }
    loading = false;
  }

  static void showInfo(String status, {ToastGravity gravity = ToastGravity.TOP}) {
    ensureFToastContextIsNotNull();
    fToast.removeQueuedCustomToasts();
    fToast.showToast(
        child: _getToastWidget(
          bgColor: Colors.black,
          itColor: Colors.white,
          iconData: Icons.info_outline,
          text: status,
        ),
        gravity: gravity);
  }

  static void showError(String status, {ToastGravity gravity = ToastGravity.TOP, Color color = Colors.white}) {
    ensureFToastContextIsNotNull();
    fToast.removeQueuedCustomToasts();
    fToast.showToast(
        child: _getToastWidget(bgColor: Colors.black, itColor: color, iconData: Icons.error_outline, text: status),
        gravity: gravity);
  }

  static void showSuccess(String status) {
    ensureFToastContextIsNotNull();
    fToast.removeQueuedCustomToasts();
    fToast.showToast(
        child: _getToastWidget(bgColor: Colors.greenAccent, itColor: Colors.black, iconData: Icons.check, text: status),
        gravity: ToastGravity.TOP);
  }

  static Widget _getToastWidget(
      {required Color bgColor, required Color itColor, required IconData iconData, required String text}) {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 24.0.w, vertical: 12.0.w),
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(25.0.w),
        color: bgColor,
      ),
      child: Row(
        mainAxisSize: MainAxisSize.min,
        children: [
          Icon(
            iconData,
            color: itColor,
          ),
          SizedBox(
            width: 12.0.w,
          ),
          Expanded(
              child: Text(
            text,
            maxLines: 3,
            overflow: TextOverflow.ellipsis,
            style: TextStyle(fontSize: 16.sp, color: itColor),
          )),
        ],
      ),
    );
  }
}
